/**
 * Filename: SettingActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/9 2:36
 */
package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.facebook.imagepipeline.core.ImagePipelineFactory;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.huanxin.DemoHelper;
import com.github.postsanf.yinian.service.BackUpService;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.DoSecretUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.hyphenate.EMCallBack;
import com.umeng.analytics.MobclickAgent;

/**
 * 设置界面
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener, ISkinUpdate {
    private Toolbar mToolbar;
    private RelativeLayout setting_exit;
    private RelativeLayout setting_clear_cache;
    private RelativeLayout setting_advice;
    private RelativeLayout setting_upload;
    private RelativeLayout setting_network;
    private RelativeLayout setting_about;
    private RelativeLayout setting_codenum;
    private RelativeLayout setting_cache_limit;
    private TextView tv_exit_switch;
    private ToggleButton numSwitch;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;
    private ImageView iv_network_3w, iv_network_wifi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_setting);
        registerBoradcastReceiver();
        BaseApplication.getInstance().mActivitys.add(this);
        initView();
    }

    private void initView() {
        mSharedPreferences = getSharedPreferences(ACTIONs.mypassword, 0);
        mEditor = mSharedPreferences.edit();
        mToolbar = (Toolbar) findViewById(R.id.setting_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);

        setting_exit = (RelativeLayout) findViewById(R.id.setting_exit);
        setting_cache_limit = (RelativeLayout) findViewById(R.id.setting_cache_limit);
        setting_clear_cache = (RelativeLayout) findViewById(R.id.setting_clear_cache);
        setting_advice = (RelativeLayout) findViewById(R.id.setting_advice);
        setting_upload = (RelativeLayout) findViewById(R.id.setting_upload);
        setting_network = (RelativeLayout) findViewById(R.id.setting_network);
        setting_codenum = (RelativeLayout) findViewById(R.id.setting_codenum);
        setting_about = (RelativeLayout) findViewById(R.id.setting_about);
        tv_exit_switch = (TextView) findViewById(R.id.tv_exit_switch);
        numSwitch = (ToggleButton) findViewById(R.id.setting_switch1);
        setting_cache_limit.setOnClickListener(this);
        setting_exit.setOnClickListener(this);
        setting_clear_cache.setOnClickListener(this);
        setting_advice.setOnClickListener(this);
        setting_upload.setOnClickListener(this);
        setting_network.setOnClickListener(this);
        setting_about.setOnClickListener(this);
        setting_codenum.setOnClickListener(this);
        SetSwitch();
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionSetNumCode);
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionSetNumCode:
                    SetSwitch();
                    break;
            }
        }
    };

    private void SetSwitch() {
        boolean bb = mSharedPreferences.getBoolean(ACTIONs.numcodepasswordbb, false);
        if (bb) {
            numSwitch.setChecked(true);
        } else {
            numSwitch.setChecked(false);
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }


    void logout() {
        final ProgressDialog pd = new ProgressDialog(this);
        String st = getResources().getString(R.string.Are_logged_out);
        pd.setMessage(st);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        DemoHelper.getInstance().logout(false, new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        Intent mIntent = new Intent(SettingActivity.this, BackUpService.class);
                        mIntent.setAction(ACTIONs.actionCancelBackupPhoto);
                        startService(mIntent);
                        intent2Activity(LoginActivity.class);
                        finish();
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(SettingActivity.this, "unbind devicetokens failed", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setting_cache_limit:
                showToast("设置缓存上限");
                break;
            case R.id.setting_exit:
                SharedPreferences.Editor ed = application.getSp_login().edit();
                ed.putString(getString(R.string.SP_YNS_PASSWORD), DoSecretUtils.doSecretStr(""));
                ed.putString(getString(R.string.LID), DoSecretUtils.doSecretStr(""));
                ed.commit();
                application.clearAllData();
                logout();
                break;
            case R.id.setting_clear_cache:
                imageLoader.clearDiskCache();
                imageLoader.clearMemoryCache();
                // 清理Fresco缓存
                ImagePipelineFactory.getInstance().getImagePipeline().clearMemoryCaches();
                ImagePipelineFactory.getInstance().getImagePipeline().clearCaches();
                ImagePipelineFactory.getInstance().getImagePipeline().clearDiskCaches();
                Snackbar.make(setting_clear_cache, "缓存清除成功", Snackbar.LENGTH_LONG)
                        .setAction("关闭", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                            }
                        }).show();
                break;
            case R.id.setting_advice:
                intent2Activity(AdviceActivity.class);
                break;
            case R.id.setting_upload:
                intent2Activity(UpLoadActivity.class);
                Intent statintentbupload = new Intent(ACTIONs.record);
                statintentbupload.putExtra("key", "上传进度_4");
                statintentbupload.putExtra("value", 1);
                sendBroadcast(statintentbupload);
                break;
            case R.id.setting_network:
                ModifyNetwork();
                Intent statintentmm = new Intent(ACTIONs.record);
                statintentmm.putExtra("key", "上传环境_4");
                statintentmm.putExtra("value", 1);
                sendBroadcast(statintentmm);
                break;
            case R.id.setting_about:
                intent2Activity(AboutActivity.class);
                break;
            case R.id.setting_codenum:
                String passwordmm = mSharedPreferences.getString(ACTIONs.numcodepasswordmm, "");
                boolean bb = mSharedPreferences.getBoolean(ACTIONs.numcodepasswordbb, false);
                if (!bb) {
                    if (passwordmm == null || passwordmm.equals("")) {
                        new AlertDialog.Builder(SettingActivity.this).setMessage("请牢记密码，否则你将无法再次进入忆年")
                                .setPositiveButton(R.string.yn_app_setmm, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        intent2Activity(SetNumCodeMM.class);
                                    }
                                }).setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                numSwitch.setChecked(false);
                            }
                        }).show();
                    } else {
                        intent2Activity(SetNumCodeMM.class);
                    }
                } else {
                    if (numSwitch.isChecked()) {
                        intent2Activity(SetNumCodeMMCancel.class);
                    }
                }
                Intent statintentmmcode = new Intent(ACTIONs.record);
                statintentmmcode.putExtra("key", "密码锁_4");
                statintentmmcode.putExtra("value", 1);
                sendBroadcast(statintentmmcode);
                break;
        }
    }

    private SharedPreferences.Editor editor;

    private void ModifyNetwork() {
        View sexView = View.inflate(this, R.layout.yn_dialog_setnetwork, null);
        LinearLayout ll_network_3w = (LinearLayout) sexView.findViewById(R.id.ll_network_3w);
        LinearLayout ll_network_wifi = (LinearLayout) sexView.findViewById(R.id.ll_network_wifi);
        iv_network_3w = (ImageView) sexView.findViewById(R.id.iv_network_3w);
        iv_network_wifi = (ImageView) sexView.findViewById(R.id.iv_network_wifi);
        SharedPreferences mSharedPreferences = getSharedPreferences(ACTIONs.mynetwork, 0);
        editor = mSharedPreferences.edit();
        String networkStr = mSharedPreferences.getString(ACTIONs.networkType, "");
        if (networkStr.equals(ACTIONs.networkOnlyWIFI)) {
            alertSexImgTo3W(false);
        } else if (networkStr.equals(ACTIONs.network3GWIFI)) {
            alertSexImgTo3W(true);
        }
        final AlertDialog alertDialog = new AlertDialog.Builder(this).show();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.setContentView(sexView);
        WindowManager.LayoutParams layout = alertDialog.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 32 * 2);
        alertDialog.getWindow().setAttributes(layout);
        ll_network_3w.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertSexImgTo3W(true);
                editor.putString(ACTIONs.networkType, ACTIONs.network3GWIFI);
                editor.commit();
                alertDialog.dismiss();
            }
        });
        ll_network_wifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertSexImgTo3W(false);
                editor.putString(ACTIONs.networkType, ACTIONs.networkOnlyWIFI);
                editor.commit();
                alertDialog.dismiss();
            }
        });
    }

    private void alertSexImgTo3W(boolean is3W) {
        if (is3W) {
            iv_network_3w.setImageResource(R.drawable.network_choose_yes);
            iv_network_wifi.setImageResource(R.drawable.network_choose_no);
        } else {
            iv_network_3w.setImageResource(R.drawable.network_choose_no);
            iv_network_wifi.setImageResource(R.drawable.network_choose_yes);
        }
    }

    @Override
    public void updateTheme() {
        if (mToolbar != null) {
            try {
                Resources mResource = SkinPackageManager.getInstance(this).mResources;
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", "drawable", "com.github.postsanf.skinby")));
                mToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", "color", "com.github.postsanf.skinby")));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", "color", "com.github.postsanf.skinby")));
                tv_exit_switch.setTextColor(mResource.getColor(mResource.getIdentifier("yncolor", "color", "com.github.postsanf.skinby")));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApplication.getInstance().mActivitys.remove(this);
        unregisterReceiver(mBroadcastReceiver);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        if (SkinPackageManager.getInstance(this).mResources != null) {
            updateTheme();
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

}
